#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from django import forms
from assoce.generic_form.views import BaseForm
from assoce.core.models import Membre
from assoce.core.models import Emprunt
from assoce.bibli.models import Livre
from datetime import datetime


class ImportForm(BaseForm):
    user = forms.ModelChoiceField(queryset=Membre.objects.all())
    reset = forms.BooleanField(label='effacer existant')
    paste = forms.CharField(widget=forms.Textarea)
    def process(self):
        data = self.cleaned_data
        if data['reset']:
            Emprunt.objects.filter(membre=data['user']).delete()
        lines = data['paste'].splitlines()
        for l in lines:
            try:
                t = l.split('\t')
                if len(t) < 5 or len(t) > 6 : continue
                
                if len(t) == 5:
                    ref, a, b, c, start = t
                    end = None
                if len(t) == 6:
                    ref, a, b, c, start, end = t
                    if end=='':
                        end=None
                    else:
                        end = parseDateTime(end)
                if len(ref)==0: continue
                print ref, start, end
                livre = Livre.objects.get(ref=ref)
                start = parseDateTime(start)
                e = Emprunt(membre=data['user'],
                            item=livre.item,
                            start=start, end=end)
                e.save()
            except Exception, v:
                print 'erreur import %s' % v
        return

def parseDateTime(s):
    d, m, y = s.split('/')
    return datetime(int(y), int(m), int(d))